import React, { useState, useEffect, useCallback, forwardRef, useImperativeHandle } from 'react';
import { Form, Row, Col, Popconfirm, Button, Input } from 'antd';
import AffixedBottom from './AffixedBottom';
import { createRecord, updateRecord } from './services/formContent';

const reqMethod = {
  add: createRecord,
  modify: updateRecord,
};

const labelCol = {
  xs: { span: 24 },
  sm: { span: 5 },
};
const wrapperCol = {
  xs: { span: 24 },
  sm: { span: 17 },
};

/**
 * 表单内容
 * @param {'add' | 'info' | 'modify' } formType
 * @param [afterSubmit] 提交成功之后的回调
 * @param [onCancel] 点击取消按钮的回调
 * @param [data] 表单数据回填
 */
const FormContent = forwardRef(({ formType, afterSubmit, onCancel, data }, formRef) => {
  const [pending, setPending] = useState(false);

  const [form] = Form.useForm();

  const handleSubmit = useCallback(() => {
    form.validateFields().then(values => {
      setPending(true);
      reqMethod[formType]({ ...values, id: data?.id })
        .then(res => {
          if (res?.success) {
            typeof afterSubmit === 'function' && afterSubmit();
          }
        })
        .finally(() => {
          setPending(false);
        });
    });
  }, [form, formType, data, afterSubmit]);

  useEffect(() => {
    form.setFieldsValue(data);
  }, [form, data]);

  useImperativeHandle(formRef, () => form, [form]);

  return (
    <AffixedBottom
      bottomContent={
        formType === 'info' ? null : (
          <>
            <Popconfirm title="确定放弃编辑？" okText="确定" cancelText="取消" onConfirm={onCancel}>
              <Button style={{ marginRight: 10 }}>取消</Button>
            </Popconfirm>
            <Button type="primary" onClick={handleSubmit} loading={pending}>
              提交
            </Button>
          </>
        )
      }
      bottomStyle={{ textAlign: 'right' }}
    >
      <Form form={form} autoComplete="off" labelCol={labelCol} wrapperCol={wrapperCol}>
        <Row gutter={24}>
          <Col xs={24} sm={24}>
            <Form.Item label="人员姓名" name="name">
              <Input placeholder="请输入人员姓名" disabled={formType === 'info'} />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </AffixedBottom>
  );
});

FormContent.displayName === 'FormContent';
export default FormContent;
